package com.party.admin.web.controller.system;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.admin.biz.system.MemberBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.input.system.SelectMemberInput;
import com.party.authorization.manager.impl.RedisTokenManager;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.PasswordUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.city.Area;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.member.*;
import com.party.core.model.system.MemberSysRole;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.SysRole;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.city.IAreaService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.member.*;
import com.party.core.service.message.IMessageService;
import com.party.core.service.message.IMessageSetService;
import com.party.core.service.notify.IMemberSetService;
import com.party.core.service.partner.IMemberPartnerService;
import com.party.core.service.partner.biz.MemberPartnerBizService;
import com.party.core.service.sign.IMemberSignService;
import com.party.core.service.system.IMemberSysRoleService;
import com.party.core.service.system.ISysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;


@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/system/member")
public class MemberController {

    protected static Logger logger = LoggerFactory.getLogger(MemberController.class);
    @Autowired
    private IMessageSetService messageSetService;
    @Autowired
    private IMessageService messageService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private RedisTokenManager redisTokenManager;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IIndustryService industryService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private IMemberBankService memberBankService;
    @Autowired
    private IMemberSysRoleService memberSysRoleService;
    @Autowired
    private IThirdPartyUserService thirdPartyUserService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IMemberSetService memberSetService;
    @Autowired
    private IMemberPartnerService memberPartnerService;
    @Autowired
    private MemberPartnerBizService memberPartnerBizService;
    @Autowired
    private IMemberGroupInfoService memberGroupInfoService;
    @Autowired
    private IThirdPartyUserInfoService thirdPartyUserInfoService;
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private ICrowdfundEventService crowdfundEventService;
    @Autowired
    private IMemberSignService memberSignService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IMemberGroupService memberGroupService;

    @Value("#{party['mic.url']}")
    private String micUrl;

    /**
     * 分销商
     *
     * @param member
     * @param page
     * @param commonInput
     * @param memberType
     * @param newStatus
     * @return
     */
    @RequestMapping(value = "distributorList")
    public ModelAndView distributorList(Member member, Page page, CommonInput commonInput, String memberType, String newStatus) {
        ModelAndView mv = new ModelAndView("system/member/distributorList");
        page.setLimit(20);
        member.setIsDistributor(1);
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        mv.addObject("input", commonInput);

        memberBizService.appendUserStatus(memberType, newStatus, params);

        List<Member> members = memberService.webListPage(member, params, page);
        mv.addObject("members", members);
        mv.addObject("page", page);

        mv.addObject("memberType", memberType);
        mv.addObject("status", newStatus);
        return mv;
    }

    /**
     * @return
     * @Author yifeng
     * @Description 用户列表
     * @Date 11:19 2019/4/29
     **/
    @RequestMapping(value = "memberList")
    public ModelAndView memberList() {
        ModelAndView mv = new ModelAndView("system/member/memberList");
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "api/list")
    public Map<String, Object> memberListData(Member member, Page page, CommonInput commonInput, String memberType, String newStatus) {
        Map<String, Object> ret = Maps.newHashMap();
        ret.put("data", Lists.newArrayList());
        ret.put("count", 0);
        ret.put("code", 0);
        try {
            Map<String, Object> params = CommonInput.appendParams(commonInput);
            params.put("showChannelDis", true);
            memberBizService.appendUserStatus(memberType, newStatus, params);

            Object isChannelDis = params.get("isChannelDis");
            if (null != isChannelDis) {
                params.put("isChannelDisRole", RoleEnum.CHANNEL_DISTRIBUTOR_ROLE.getCode());
            }
            Object isCosponsor = params.get("isCosponsor");
            if (null != isCosponsor) {
                params.put("isChannelDisRole", RoleEnum.COSPONSOR_ROLE.getCode());
            }

            long start = System.currentTimeMillis();
            List<Member> members = memberService.webListPage(member, params, page);
            long end = System.currentTimeMillis();
            logger.info("用户列表加载用时：{}(ms)", (end - start));

            ret.put("count", page.getTotalCount());
            ret.put("data", members);
        } catch (Exception e) {
            logger.error("用户列表数据异常", e);
        }
        return ret;
    }

    @ResponseBody
    @RequestMapping("save")
    public AjaxResult save(Member member, String type) {
        try {
            member = memberBizService.saveBiz(member, Member.MEMBER_PERSONAL);
            memberBizService.saveExpert(member);
        } catch (Exception e) {
            logger.error("用户保存异常", e);
            return AjaxResult.error("用户保存异常");
        }
        return AjaxResult.success((Object) type);
    }


    /**
     * 分销商
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "distributorForm")
    public ModelAndView distributorForm(Member member) {
        ModelAndView mv = new ModelAndView("system/member/distributorForm");
        toForm(member, mv);
        return mv;
    }

    /**
     * 合伙人
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "copartnerForm")
    public ModelAndView coparnterForm(Member member) {
        ModelAndView mv = new ModelAndView("system/member/copartnerForm");
        toForm(member, mv);
        return mv;
    }

    /**
     * 合伙人
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "resetPwdForm")
    public ModelAndView resetPwdForm(String memberId, String isGroup) {
        ModelAndView mv = new ModelAndView("system/member/resetPwdForm");
        mv.addObject("memberId", memberId);
        mv.addObject("isGroup", isGroup);
        return mv;
    }

    /**
     * ceo户外联盟个人
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "personForm")
    public ModelAndView personForm(Member member) {
        ModelAndView mv = new ModelAndView("system/member/personForm");
        mv.addObject("from", "person");
        toForm(member, mv);
        return mv;
    }

    /**
     * 新增/编辑
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "memberForm")
    public ModelAndView memberForm(Member member) {
        ModelAndView mv = new ModelAndView("system/member/memberForm");
        mv.addObject("type", 3);
        toForm(member, mv);
        return mv;
    }

    public void toForm(Member member, ModelAndView mv) {
        String memberId = member.getId();
        if (StringUtils.isNotEmpty(memberId)) {
            member = memberService.get(memberId);
            mv.addObject("member", member);

            if (StringUtils.isNotEmpty(member.getIndustry())) {
                Industry industry = industryService.get(member.getIndustry());
                mv.addObject("inParent", industry.getParentId());
            }

            if (StringUtils.isNotEmpty(member.getCity())) {
                Area area = areaService.get(member.getCity());
                mv.addObject("arParent", area.getParentId());
            }
        }

/*        Industry industry = new Industry();
        industry.setParentId("0");
        List<Industry> industries = industryService.list(industry);
        mv.addObject("industries", industries);*/

/*        Area area = new Area();
        area.setParentId("1");
        List<Area> areas = areaService.list(area);
        mv.addObject("areas", areas);*/
    }

    @RequestMapping(value = "memberView")
    public ModelAndView memberView(String id) {
        ModelAndView modelAndView = new ModelAndView("system/member/memberInfo");
        String memberId = RealmUtils.getCurrentUser().getId();
        try {
            String industryId = null;
            String cityId = null;
            Member member = memberService.get(id);
            if (null == member) {
                MemberGroup memberGroup = memberGroupService.get(id);
                if (null == memberGroup) {
                    return modelAndView;
                } else {
                    //替换手机号
                    String phone = memberBizService.replacePhone(memberId, memberGroup.getMobile());
                    memberGroup.setMobile(phone);

                    industryId = memberGroup.getIndustry();
                    cityId = memberGroup.getCity();
                    modelAndView.addObject("member", memberGroup);
                    modelAndView.addObject("isGroup", true);
                }
            } else {
                industryId = member.getIndustry();
                cityId = member.getCity();

                //替换手机号
                String phone = memberBizService.replacePhone(memberId, member.getMobile());
                member.setMobile(phone);

                modelAndView.addObject("member", member);
            }
            if (!Strings.isNullOrEmpty(industryId)) {
                Industry industry = industryService.get(industryId);
                modelAndView.addObject("industry", industry);
            }
            if (!Strings.isNullOrEmpty(cityId)) {
                Area area = areaService.get(cityId);
                modelAndView.addObject("city", area);
            }

        } catch (Exception e) {
            logger.error("查询会员信息异常", e);
        }
        return modelAndView;
    }

    /**
     * 用户审核
     *
     * @param id
     * @param userStatus
     * @return
     */
    @ResponseBody
    @RequestMapping("verify")
    public AjaxResult verify(String id, Integer userStatus) {
        try {
            Member member = memberService.get(id);
            member.setUserStatus(userStatus);
            memberService.update(member);

            /*MessageSet messageSet = messageSetService.findByMemberId(id);
            if (messageSet != null) {
                if ((1 == messageSet.getSysTip()) && StringUtils.isNotBlank(member.getId())) {
                    if (1 == member.getUserStatus()) {
                        notifySendService.sendMemberPass(member);
                    } else if (2 == member.getUserStatus()) {
                        notifySendService.sendMemberRefuse(member);
                    }
                }
            }*/
        } catch (Exception e) {
            logger.error("审核用户异常{}", e);
            return new AjaxResult(false);
        }
        return new AjaxResult(true);
    }

    /**
     * 前端行业分类联动
     *
     * @param industryId
     * @return
     */
    @ResponseBody
    @RequestMapping("getIndustryByParentId")
    public List<Industry> getIndustryByParentId(String industryId) {
        Industry industry = new Industry();
        industry.setParentId(industryId);
        List<Industry> industries = industryService.list(industry);
        return industries;
    }

    /**
     * 前端城市联动
     *
     * @param cityId
     * @return
     */
    @ResponseBody
    @RequestMapping("getCityByParentId")
    public List<Area> getCityByParentId(String cityId) {
        Area area = new Area();
        area.setParentId(cityId);
        List<Area> areas = areaService.list(area);
        return areas;
    }

    /**
     * 验证用户名或者手机号
     *
     * @param property
     * @param userId
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping("checkUniqueProperty")
    public AjaxResult checkUniqueProperty(String key, String value, String userId, Integer type, String roleName) {
        if (StringUtils.isEmpty(key)) {
            return AjaxResult.error("请选择验证用户名或是手机号");
        }
        if (StringUtils.isEmpty(value)) {
            return AjaxResult.error("请输入需要验证的值");
        }
        if ("mobile".equals(key) && null == type) {
            return AjaxResult.error("用户类型不能为空");
        }
        try {
            List<Member> members = memberService.checkUserName(key, value, userId, type);
            if (members.size() > 0) {
                if (members.size() == 1) {
                    if (StringUtils.isNotEmpty(userId) && !userId.equals(members.get(0).getId())) {
                        return AjaxResult.success(false);
                    }
                    if (StringUtils.isNotEmpty(roleName)) {
                        boolean hasPartner = sysRoleService.hasRole(members.get(0).getId(), roleName);
                        if (hasPartner) {
                            return AjaxResult.success(false);
                        } else {
                            return AjaxResult.success(true);
                        }
                    }
                }
                return AjaxResult.success(false);
            }
            return AjaxResult.success(true);
        } catch (Exception e) {
            logger.error("验证用户名或手机号异常", e);
            return AjaxResult.error("验证用户名或手机号异常");
        }
    }

    /**
     * 验证用户密码
     *
     * @param password
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("checkPassword")
    public boolean checkPassword(String password, String userId) {
        Member member = memberService.get(userId);
        return PasswordUtils.validatePassword(password, member.getPassword());
    }

    /**
     * 分销开启开关
     *
     * @param id            会员编号
     * @param isDistributor 分销状态
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/distribution/switch")
    public AjaxResult distributionSwitch(String id, Integer isDistributor) {
        AjaxResult ajaxResult = new AjaxResult();
        Member member = memberService.get(id);
        if (null == member) {
            ajaxResult.setDescription("用户不存在");
            return ajaxResult;
        }
        member.setIsDistributor(isDistributor);
        member.setType(Member.MEMBER_PERSONAL);
        SysRole sysRole = sysRoleService.uniqueProperty(new SysRole("", "distributor"));
        if (sysRole != null) {
            if (isDistributor == 1) {
                MemberSysRole t = new MemberSysRole(member.getId(), sysRole.getId());
                memberSysRoleService.insert(t);
            } else {
                memberSysRoleService.deleteByRoleIdAndMemberId(sysRole.getId(), member.getId());
            }
        }
        memberService.update(member);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 修改密码
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("updatePwd")
    public AjaxResult updatePwd(Member member) {
        try {
            if (StringUtils.isNotEmpty(member.getId())) {
                Member t = memberService.get(member.getId());

                if (StringUtils.isNotEmpty(member.getPassword())) {
                    String encryptPassword = PasswordUtils.encryptPassword(member.getPassword());
                    t.setPassword(encryptPassword);
                    memberService.update(t);
                }
            }
        } catch (Exception e) {
            logger.error("修改密码异常", e);
            return new AjaxResult(false);
        }
        return new AjaxResult(true);
    }

    /**
     * 设置或取消设置达人
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "setExpert")
    public AjaxResult setExpert(String id, Integer isExpert) {
        try {
            Member member = memberService.get(id);
            member.setType(Member.MEMBER_PERSONAL);
            SysRole sysRole = sysRoleService.uniqueProperty(new SysRole("", "expert"));
            if (isExpert == 0) {
                member.setIsExpert(0);
                memberService.update(member);
                memberBizService.saveExpert(member);
                memberSysRoleService.deleteByRoleIdAndMemberId(sysRole.getId(), member.getId());
            } else if (isExpert == 1) {
                member.setIsExpert(1);
                memberService.update(member);
                memberBizService.saveExpert(member);
                MemberSysRole t = new MemberSysRole(member.getId(), sysRole.getId());
                memberSysRoleService.insert(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 根据用户手机或用户名查询
     *
     * @param property
     * @param value
     * @return
     */
    @ResponseBody
    @RequestMapping("findMemberByPhoneOrName")
    public AjaxResult findMemberByPhoneOrName(String property, String value) {
        try {
            List<Map<String, Object>> list = memberService.findMemberByPhoneOrName(property, value, Member.MEMBER_PERSONAL);
            return AjaxResult.success(list);
        } catch (Exception e) {
            logger.error("根据用户手机或用户名查询失败", e);
            return new AjaxResult(false);
        }

    }

    @ResponseBody
    @RequestMapping("getMember")
    public AjaxResult getMember(String id) {

        Map<String, Object> map = new HashMap<String, Object>();

        Member member = memberService.get(id);
        String inParent = "";
        if (StringUtils.isNotEmpty(member.getIndustry())) {
            Industry industry = industryService.get(member.getIndustry());
            inParent = industry.getParentId();
        }

        String arParent = "";
        if (StringUtils.isNotEmpty(member.getCity())) {
            Area area = areaService.get(member.getCity());
            arParent = area.getParentId();
        }

        map.put("inParent", inParent);
        map.put("arParent", arParent);
        map.put("member", member);
        return AjaxResult.success(map);
    }

    /**
     * 获取第三方授权列表
     *
     * @param memberId
     * @return
     */
    @RequestMapping("getAuthList")
    public ModelAndView getAuthList(String memberId) {
        ModelAndView mv = new ModelAndView("system/member/selAuthType");
        List<Map<String, Object>> authList = thirdPartyUserService.getAuthList(memberId);
        mv.addObject("authList", authList);
        mv.addObject("memberId", memberId);
        return mv;
    }

    /**
     * 删除第三方授权信息
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("removeAuth")
    public AjaxResult removeAuth(String ids, String memberId) {
        try {
            String[] split = ids.split(",");
            for (String thirdPartyUserId : split) {
                thirdPartyUserService.delete(thirdPartyUserId);
                thirdPartyUserInfoService.deleteByThirdPartyUserId(thirdPartyUserId);
            }

            if (StringUtils.isNotEmpty(memberId)) {
                redisTokenManager.delRelationshipByKey(memberId);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("解除授权关系异常", e);
            return AjaxResult.error("解除授权关系异常");
        }
    }

    @RequestMapping(value = "memberViewWithShare")
    public ModelAndView memberViewWithShare(String id, String projectId) {
        ModelAndView mv = new ModelAndView("system/member/memberInfoWithShare");
        try {
            if (StringUtils.isNotEmpty(id)) {
                Member member = memberService.get(id);
                if (StringUtils.isNotEmpty(member.getIndustry())) {
                    Industry industry = industryService.get(member.getIndustry());
                    mv.addObject("industry", industry);
                }

                if (StringUtils.isNotEmpty(member.getCity())) {
                    Area area = areaService.get(member.getCity());
                    mv.addObject("city", area);
                }

                //替换手机号
                String memberId = RealmUtils.getCurrentUser().getId();
                String phone = memberBizService.replacePhone(memberId, member.getMobile());
                member.setMobile(phone);

                mv.addObject("member", member);

                String url = micUrl + "project/project_detail.html?id=" + projectId;
                CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);
                if (null != crowdfundEvent && YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                    url = micUrl + "project/project_multi_detail.html?id=" + projectId;
                }
                mv.addObject("zcLink", url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * 合作商简易信息
     * //     * @param page 分页信息
     * //     * @param realName 合作商名
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "partnerInfoSimple")
    public AjaxResult partnerInfoSimple(@Param(value = "realname") String realname, Page page) {
        AjaxResult ajaxResult = new AjaxResult();
        Member member = new Member();
        member.setIsPartner(1);
        member.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        if (StringUtils.isNotBlank(realname)) {
            member.setRealname(realname);
        }
        List<Member> list = memberService.partnerSimpleListPage(member, page);
        if (list == null) {
            ajaxResult.setSuccess(false);
            return ajaxResult;
        }
        ajaxResult.setData(list);
        ajaxResult.setPage(page);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 获取供应商
     *
     * @param member
     * @param page
     * @return
     */
    @RequestMapping("selectMember")
    public ModelAndView selectPartnerOr(SelectMemberInput memberInput, Page page) {
        ModelAndView mv = new ModelAndView("system/member/selectMember");
        if (null != memberInput.getPageType()) {
            mv.setViewName("system/member/selectPartner");
        }
        if (null != memberInput.getIsAdmin()) {
            page.setLimit(10);
            mv.setViewName("system/member/selectAdmin");
        }
        if (null != memberInput.getIsPartner() || null != memberInput.getIsAdmin()) {
            MemberGroup memberGroup = new MemberGroup();
            memberGroup.setRealname(memberInput.getRealname());
            memberGroup.setUsername(memberInput.getUsername());
            memberGroup.setMobile(memberInput.getMobile());
            memberGroup.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            if (null != memberInput.getIsPartner()) {
                memberGroup.setOpenStatus(1);
            }
            memberGroup.setIsPartner(memberInput.getIsPartner());
            memberGroup.setIsAdmin(memberInput.getIsAdmin());
            List<PartnerInfoDetails> memberList = memberGroupService.getPartnerListData(memberGroup, page);
            mv.addObject("memberList", memberList);
        } else if (null != memberInput.getIsDistributor() || null != memberInput.getIsCopartner()) {
            Member member = new Member();
            member.setRealname(memberInput.getRealname());
            member.setUsername(memberInput.getUsername());
            member.setMobile(memberInput.getMobile());
            member.setIsCopartner(memberInput.getIsCopartner());
            member.setIsDistributor(memberInput.getIsDistributor());
            member.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            List<Member> memberList = memberService.listPage(member, page);
            mv.addObject("memberList", memberList);
        }

        mv.addObject("page", page);
        mv.addObject("memberInput", memberInput);
        return mv;
    }

    /**
     * 合伙人-机构
     *
     * @param member
     * @param page
     * @param commonInput
     * @param memberType
     * @param newStatus
     * @return
     */
    @RequestMapping(value = "copartnerList")
    public ModelAndView copartnerList(Member member, Page page, CommonInput commonInput, String memberType, String newStatus, Integer isCopartnerDis) {
        ModelAndView mv = new ModelAndView("system/member/copartnerList");
        try {
            page.setLimit(20);
//            member.setIsCopartner(1);
//            member.setType(2);
            Map<String, Object> params = CommonInput.appendParams(commonInput);

            mv.addObject("input", commonInput);

            memberBizService.appendUserStatus(memberType, newStatus, params);

            params.put("code", RoleEnum.CHANNEL_DISTRIBUTOR_ROLE.getCode());//只加载合伙人角色的数据列表
            if (null != isCopartnerDis && isCopartnerDis.equals(YesNoStatus.YES.getCode())) {
                params.put("code", RoleEnum.COPARTNER_DISTRIBUTOR_ROLE.getCode());
            } else {
                params.put("isCopartnerDis", isCopartnerDis);
            }
            List<Member> members = memberService.webListPage(member, params, page);
            mv.addObject("members", members);
            mv.addObject("page", page);

            mv.addObject("memberType", memberType);
            mv.addObject("status", newStatus);
            mv.addObject("isCopartnerDis", isCopartnerDis);
        } catch (Exception e) {
            logger.error("合伙人列表异常", e);
        }
        return mv;
    }

    /**
     * 合伙人-个人
     *
     * @param member
     * @param page
     * @param commonInput
     * @param memberType
     * @param newStatus
     * @return
     */
    @RequestMapping(value = "personList")
    public ModelAndView personalList(Member member, Page page, CommonInput commonInput, String memberType, String newStatus) {
        ModelAndView mv = new ModelAndView("system/member/personalList");
        try {
            page.setLimit(20);
            member.setIsCopartner(1);
            member.setType(1);
            Map<String, Object> params = CommonInput.appendParams(commonInput);

            mv.addObject("input", commonInput);

            memberBizService.appendUserStatus(memberType, newStatus, params);

            List<Member> members = memberService.webListPage(member, params, page);
            mv.addObject("members", members);
            mv.addObject("page", page);

            mv.addObject("memberType", memberType);
            mv.addObject("status", newStatus);
        } catch (Exception e) {
            logger.error("合伙人列表异常", e);
        }
        return mv;
    }


    /**
     * 保存CEO户外联盟机构
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("saveCopartner")
    public AjaxResult saveCopartner(Member member) {
        try {
            member.setIsCopartner(YesNoStatus.YES.getCode());
            member.setRealname(member.getCompany());
            memberBizService.saveBiz(member, Constant.MEMBER_ORGANIZATION);
            memberBizService.saveExpert(member);
        } catch (Exception e) {
            logger.error("CEO户外联盟机构保存异常", e);
            return AjaxResult.error("CEO户外联盟机构保存异常");
        }
        return AjaxResult.success();
    }

    /**
     * 保存CEO户外联盟个人
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("savePerson")
    public AjaxResult savePerson(Member member) {
        try {
            member.setIsCopartner(YesNoStatus.YES.getCode());
            memberBizService.saveBiz(member, Member.MEMBER_PERSONAL);
            memberBizService.saveExpert(member);
        } catch (Exception e) {
            logger.error("CEO户外联盟个人保存异常", e);
            return AjaxResult.error("CEO户外联盟个人保存异常");
        }
        return AjaxResult.success();
    }

    /**
     * 保存分销商
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("saveDistributor")
    public AjaxResult saveDistributor(Member member) {
        try {
            member.setIsDistributor(YesNoStatus.YES.getCode());
            memberBizService.saveBiz(member, Member.MEMBER_PERSONAL);
            memberBizService.saveExpert(member);
        } catch (Exception e) {
            logger.error("分销商保存异常", e);
            return AjaxResult.error("用户保存异常");
        }
        return AjaxResult.success();
    }

    /**
     * 初始化联合发起人
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("initRepresentData")
    public AjaxResult initRepresentData() {
        try {
            memberBizService.initRepresentData();
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("初始化联合发起人异常", e);
            return AjaxResult.error("初始化联合发起人异常");
        }
    }

    /**
     * 解绑手机
     *
     * @param memberId 用户id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "unbindPhone", method = RequestMethod.POST)
    public AjaxResult unbindPhone(String memberId) {
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error("用户编号不能为空");
        }
        try {
            Member member = memberService.get(memberId);
            member.setMobile("");
            memberService.update(member);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("解绑手机异常", e);
            return AjaxResult.error("解绑手机异常");
        }
    }

    /**
     * 初始化合作商附属表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("initMemberPartner")
    public String initMemberPartner() {
        memberPartnerBizService.init();
        return "OK";
    }

    /**
     * 解除身份证实名认证
     *
     * @param memberId 用户id
     * @return
     */
    @ResponseBody
    @RequestMapping("unCertified")
    public AjaxResult unCertified(String memberId) {
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error("用户id不能为空");
        }
        try {
            Member member = memberService.get(memberId);
            member.setIsCertified(YesNoStatus.NO.getCode());
            member.setUpdateDate(null);
            memberService.update(member);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("解绑认证异常", e);
            return AjaxResult.error("解绑认证异常");
        }
    }

    /**
     * 设置或取消设置达人
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "setCopartnerDistribution")
    public AjaxResult setCopartnerDistribution(String ids, Integer isDistribution) {
        try {
            if (StringUtils.isEmpty(ids)) {
                return AjaxResult.error("用户id不能为空");
            }
            for (String id : ids.split(",")) {
                boolean hasCopartnerDis = sysRoleService.hasRole(id, RoleEnum.COPARTNER_DISTRIBUTOR_ROLE.getCode());
                SysRole sysRole = sysRoleService.uniqueProperty(new SysRole("", RoleEnum.COPARTNER_DISTRIBUTOR_ROLE.getCode()));
                if (isDistribution == 0 && hasCopartnerDis) {
                    memberSysRoleService.deleteByRoleIdAndMemberId(sysRole.getId(), id);
                } else if (isDistribution == 1 && !hasCopartnerDis) {
                    MemberSysRole t = new MemberSysRole(id, sysRole.getId());
                    memberSysRoleService.insert(t);
                }
            }
        } catch (Exception e) {
            logger.error("设置合伙人分销异常", e);
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }


    /**
     * 众筹结束跟进初始化方法
     */
    @ResponseBody
    @RequestMapping(value = "initMemberGroupInfo")
    public AjaxResult initMemberGroupInfo() {
        /**初始化默认状态为处理完成*/
        List<Member> stringList = memberGroupInfoService.getMemberId();
        for (Member member : stringList) {
            MemberGroupInfo MemberGroupInfo = new MemberGroupInfo();
            MemberGroupInfo.setMemberId(member.getId());
            memberGroupInfoService.insert(MemberGroupInfo);
        }
        return AjaxResult.success();
    }


    /**
     * @Description:将符合要求合作商的“真实名称”填充到“公司全称”
     * @Param: [member]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019-02-26-0026
     */
    @ResponseBody
    @RequestMapping(value = "updatePartnerInfo")
    public AjaxResult updatePartnerInfo() {
        try {
            List<Member> members = memberService.getMemberCompanyIsNull();
            for (Member m : members) {
                m.setCompany(m.getFullname());
                memberService.update(m);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping(value = "initType")
    public AjaxResult initType() {
        try {
            // 合作商 type更新为2
            memberService.updateType(Member.MEMBER_ORGANIZATION, "is_partner");
            // 合作渠道 type更新为2
            memberService.updateType(Member.MEMBER_ORGANIZATION, "is_cosponsor");

            // 联合发起人 type为1
            memberService.updateType(Member.MEMBER_PERSONAL, "is_copartner");
            // 达人 type为1
            memberService.updateType(Member.MEMBER_PERSONAL, "is_expert");
            // 分销商 type为1
            memberService.updateType(Member.MEMBER_PERSONAL, "is_distributor");

            // 管理员 type为3
            memberService.updateType(Member.MEMBER_PLATFORM, "is_admin");

            // 合伙人 type为1
            memberService.updateType2();

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("更新type异常", e);
            return AjaxResult.error("更新type异常");
        }
    }
}